﻿using CodeGenerator.Common;
using CodeGenerator.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;

namespace CodeGenerator
{
    public partial class frmContent : DockContent
    {

        #region 属性
        private Connection connectionModel;
        private string content;
        private string databaseName;
        private bool isView = false;
        private string tableName;
        public Connection ConnectionModel
        {
            get =>
                this.connectionModel;
            set
            {
                this.connectionModel = value;
            }
        }

        public string Content
        {
            get =>
                this.content;
            set
            {
                this.content = value;
            }
        }

        public string DatabaseName
        {
            get =>
                this.databaseName;
            set
            {
                this.databaseName = value;
            }
        }

        public bool IsView
        {
            get =>
                this.isView;
            set
            {
                this.isView = value;
            }
        }

        public string TableName
        {
            get =>
                this.tableName;
            set
            {
                this.tableName = value;
            }
        }

        private DataTable columnsdt = null;
        private SaveFileDialog saveEntity;
        #endregion 
        public frmContent()
        {
            InitializeComponent();
           
            FileInfo[] files = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Template"))
                .GetFiles("*.tpl", SearchOption.AllDirectories);
            foreach (FileInfo info in files)
            {
                this.tplComboBox.Items.Add(info.Name);
            }
            this.tplComboBox.SelectedIndex = 0;
            string path = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Template", this.tplComboBox.SelectedText);
            if (File.Exists(path))
            {
                this.tplContent.Text = FileHelper.Read(path, null);
            }
            saveEntity = new SaveFileDialog();
        }
        DataGridViewCellStyle style = new DataGridViewCellStyle();
        DataGridViewCellStyle style2 = new DataGridViewCellStyle();
        private void frmContent_Load(object sender, EventArgs e)
        {
            this.gridColumns.AllowUserToAddRows = false;
            this.gridColumns.AllowUserToDeleteRows = false;
            this.gridColumns.AllowUserToOrderColumns = true;

            style.Alignment = DataGridViewContentAlignment.MiddleLeft;
            style.BackColor = SystemColors.Control;
            style.Font = new Font("宋体", 9f, FontStyle.Regular, GraphicsUnit.Point, 0x86);
            style.ForeColor = SystemColors.WindowText;
            style.SelectionBackColor = SystemColors.Highlight;
            style.SelectionForeColor = SystemColors.HighlightText;
            style.WrapMode = DataGridViewTriState.True;

            this.gridColumns.ColumnHeadersDefaultCellStyle = style;
            this.gridColumns.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            style2.Alignment = DataGridViewContentAlignment.MiddleLeft;
            style2.BackColor = SystemColors.Window;
            style2.Font = new Font("宋体", 9f, FontStyle.Regular, GraphicsUnit.Point, 0x86);
            style2.ForeColor = SystemColors.ControlText;
            style2.SelectionBackColor = SystemColors.Highlight;
            style2.SelectionForeColor = SystemColors.HighlightText;
            style2.WrapMode = DataGridViewTriState.False;
            this.gridColumns.DefaultCellStyle = style2;
            this.gridColumns.Dock = DockStyle.Top;
            this.gridColumns.Location = new Point(3, 3);
            this.gridColumns.Name = "gridColumns";
            this.gridColumns.RowTemplate.Height = 23;
            IDbObject obj2 = null;
            DatabaseType sqlServer = DatabaseType.SqlServer;
           
            if (ConnectionModel.DbType.Equals(sqlServer.ToString()))
            {
                obj2 = new DbMSSQLObject(ConnectionModel.ConnectionString);
            }
            else
            {
                obj2 = new DbMySQLObject(ConnectionModel.ConnectionString);
                sqlServer = DatabaseType.MySql;
                
            }
            this.columnsdt = obj2.GetColumnInfoList(this.DatabaseName, this.TableName);
            this.gridColumns.DataSource = this.columnsdt;
            
            
            this.txtClassName.Text = Utils.ToCamelName(this.TableName.Trim());
            this.txtnamespace.Text = Utils.ReadNamespace();

            this.txtContent.ContextMenuStrip = this.cmsSave;

            this.cbToupperFrstword.Checked = true;
        }

        private void tplComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            string filePath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Template", (sender as ComboBox).SelectedItem.ToString());
            this.tplContent.Text = FileHelper.Read(filePath, null);
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if ((sender as TabControl).SelectedTab.Text == "生成代码")
            {
                if (string.IsNullOrEmpty(this.txtnamespace.Text))
                {
              
                    Utils.MessageBoxShow("命名空间不能为空!");
                }
                else if (string.IsNullOrEmpty(this.txtClassName.Text))
                {
                    Utils.MessageBoxShow("类名不能为空!");
                }
                else
                {
                    Utils.WriteNamespace(this.txtnamespace.Text);
                    List<ColumnInfo> columnInfos = Utils.GetColumnInfos(this.columnsdt);
                    
                    this.txtContent.Text = new EntityBuilder(this.TableName, this.txtnamespace.Text, this.txtClassName.Text, columnInfos, this.IsView, this.cbToupperFrstword.Checked, this.ConnectionModel.DbType).Builder(this.tplContent.Text);
                    this.tabControl1.SelectedIndex = 1;
                }
            }
        }

        //保存代码
        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.saveEntity.FileName = this.txtClassName.Text;
            this.saveEntity.Filter = "CS 文件|*.cs";
            if (this.saveEntity.ShowDialog() == DialogResult.OK)
            {
                using (StreamWriter writer = new StreamWriter(this.saveEntity.FileName, false, Encoding.UTF8))
                {
                    writer.Write(this.txtContent.Text);
                    writer.Close();
                }
            }
        }
    }
}
